﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Services.Interface;
using HanGu.Common;
using HanGu.CRM.Controllers;
using System.Net.Mail;
using System.Text.RegularExpressions;

namespace HanGu.CRM.Areas.Message.Controllers
{
    public class DefaultController : AdminBaseController
    {

        //
        // GET: /Message/

        public ActionResult MsgByMember(int id = 0)
        {
            SearchParma.Pagination.IsPaging = false;
            GetDDL();
            ViewData["MsgMemberID"] = id;
            var msgList = serviceMessage.GetMsgByMemberID(id, SearchParma.SubAssignedIn);
            return View(msgList);
        }

        public ActionResult Index(int? memberID = null)
        {
            SearchParma.Pagination.PageSize = 100;
            ViewData["update"] = CurentUser.Roles.SingleOrDefault(c => c.ID == "Message_5");//修改
            ViewData["reSend"] = CurentUser.Roles.SingleOrDefault(c => c.ID == "Message_6");//重发
            ViewData["goSend"] = CurentUser.Roles.SingleOrDefault(c => c.ID == "Message_7");//转发
            if (memberID.HasValue)
            {
                SearchParma.IntObj1 = memberID.Value;

            }
            else
            {
                SearchParma.IntObj1 = -1;
            }
            GetDDL();
            return View(GetMessageList());
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {

            SearchParma.Pagination.RowCount = null;
            int type_ = -1;
            if (!string.IsNullOrEmpty(Request["IntObj1"]))
            {
                int.TryParse(Request["IntObj1"], out type_);
            }
            SearchParma.IntObj1 = type_;
            int memberid = 0;
            int.TryParse(Request["IntObj2"], out memberid);
            SearchParma.IntObj2 = memberid;
            SearchParma.Suitabler = Request["Suitabler"];
            GetDDL(SearchParma.IntObj1);
            return View(GetMessageList());
        }

        List<HanGu.Entity.Message> GetMessageList()
        {

            List<HanGu.Entity.Message> messageList = serviceMessage.GetAll(base.SearchParma);
            ViewData["RowCount"] = SearchParma.Pagination.RowCount;
            return messageList;
        }
        void GetDDL(object selectedValue = null)
        {
            var lst = serviceDict.GetByGroupName("AccessCusType");
            SelectList sList = new SelectList(lst, "Key", "Value", selectedValue);
            ViewData["AccessCusType"] = sList;
            //ViewData["members"] = new SelectList(serviceMemberInfo.GetAll(SearchParma), "ID", "UserName");
        }

        public ActionResult Create(int id = 0)
        {
            int memberid = 0;
            int.TryParse(Request["memberid"], out memberid);
            HanGu.Entity.Message message = new HanGu.Entity.Message()
            {
                GUID = HanGu.Common.Helper.GetGuid,
                MemberID = memberid,
                Type = 1,
                Receiver = Request["reciever"],
                CreateTime = DateTime.Now,
                Creator = CurentUser.UserName
            };
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
            }
            else
            {
                message.Receiver = Request["reciever"];
            }
            if (Request["action"] == "rSend")
            {
                message.ID = 0;
            }
            GetDDL(message.Type);
            base.SearchParma.Pagination.IsPaging = false;
            //ViewData["Parents"] = servicesManager.GetAll(base.SearchParma);
            ViewData["Parents"] = new SelectList(GetManagersByLevel(false), "ID", "User");
            var members = serviceMemberInfo.GetMemberName();
            string membersJson = string.Empty;
            if (members != null && members.Count > 0)
            {
                membersJson = string.Join("','", members);
            }
            ViewData["Members"] = string.Format("['{0}']", membersJson);
            return View(message);
        }

        //
        // POST: /Message/Create

        [HttpPost]
        [ValidateInput(false)]
        public string Create(FormCollection collection)
        {
            try
            {
                bool tag = false;
                HanGu.Entity.Message message = new HanGu.Entity.Message();
                string receivers = Request["SMS.Receiver"];
                TryUpdateModel(message, collection);
                message.Receiver = receivers;
                message.Creator = CurentUser.UserName;
                message.CreateTime = DateTime.Now;
                message.IsCust = true;
                message.Manager = Request["Manager"];

                Regex reg = new Regex(@"\[\d+\]");
                var match = reg.Match(message.MemberName);
                bool isMatch = match != null && !string.IsNullOrEmpty(match.Value);
                if (isMatch)
                {
                    string memberidstr = match.Value.Replace("[", "").Replace("]", "");
                    int memberid = 0;
                    if (int.TryParse(memberidstr, out memberid))
                    {
                        message.MemberID = memberid;
                    }
                    else
                    {
                        isMatch = false;
                    }

                }
                if (!isMatch)
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.InvaildMember, navTabId, "", "");
                    return "{" + ajaxStr + "}";
                }

                if (!message.CreatorID.HasValue || message.CreatorID == 0)
                {
                    message.CreatorID = CurentUser.CurrentUserInfo.ID;
                }

                var member = serviceMemberInfo.GetByID(message.MemberID);
                var members = new List<HanGu.Entity.MemberInfo>() { member };
                if (message.ID > 0)
                {
                    tag = serviceMessage.Update(message, members);
                }
                else
                {
                    tag = serviceMessage.Add(message, members);
                }


                if (tag)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");
                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }
        public ActionResult MoveMember()
        {
            ViewData["Parents"] = new SelectList(GetManagersByLevel(false), "ID", "User");
            return View();
        }

        public ActionResult SMSMember(int id = 0)
        {
            HanGu.Entity.Message message = new HanGu.Entity.Message()
            {
                GUID = HanGu.Common.Helper.GetGuid,
                MemberID = 0,
                Type = 3,
                Receiver = Request["tels"],
                CreateTime = DateTime.Now,
                Creator = CurentUser.UserName
            };
            ViewData["membersID"] = Request["membersID"];
            ViewData["membersName"] = Request["membersName"];
            ViewData["tels"] = Request["tels"];
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
            }

            if (Request["action"] == "rSend")
            {
                message.ID = 0;
            }
            return View(message);
        }

        public ActionResult reSMS(int id = 0)
        {
            int memberid = 0;
            int.TryParse(Request["memberid"], out memberid);
            HanGu.Entity.Message message = new HanGu.Entity.Message();
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
                var vwmessage = serviceMessage.GetMsgByID(id);
                if (vwmessage != null)
                {
                    ViewData["membersID"] = string.Join(",", vwmessage.Select(c => c.MemberID).ToArray());
                    ViewData["membersName"] = string.Join(",", vwmessage.Select(c => c.RealName).ToArray());
                    ViewData["tels"] = string.Join(",", vwmessage.Select(c => c.Tel).ToArray());
                }
                message.CreateTime = DateTime.Now;
                message.Creator = CurentUser.UserName;
            }

            return View(message);
        }

        public ActionResult SMS(int id = 0)
        {
            int memberid = 0;
            int.TryParse(Request["memberid"], out memberid);
            HanGu.Entity.Message message = new HanGu.Entity.Message()
            {
                GUID = HanGu.Common.Helper.GetGuid,
                MemberID = memberid,
                Type = 3,
                //Title = "发送短信【" + memberid + "】",
                Receiver = Request["reciever"],
                CreateTime = DateTime.Now,
                Creator = CurentUser.UserName
            };
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
            }
            else
            {
                message.Receiver = Request["reciever"];
            }
            if (Request["actiontype"] == "goSend")
            {
                message.Receiver = string.Empty;
            }
            return View(message);
        }

        //
        // POST: /Message/Create

        [HttpPost]
        [ValidateInput(false)]
        public string SMS(FormCollection collection)
        {
            try
            {
                string memberStr = Request["MemberIDs"];
                if (string.IsNullOrEmpty(memberStr))
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.InvalidMembers, navTabId, "", "");
                }
                else
                {
                    bool tagSMS = false;
                    HanGu.CRM.SMS smsObj = new HanGu.CRM.SMS();
                    HanGu.Entity.Message message = new HanGu.Entity.Message();
                    string receivers = Request["SMS.Receiver"] ?? Request["Receiver"];
                    TryUpdateModel(message, collection);
                    message.Receiver = receivers;
                    message.Creator = CurentUser.UserName;
                    message.CreateTime = DateTime.Now;
                    if (!message.CreatorID.HasValue || message.CreatorID == 0)
                    {
                        message.CreatorID = CurentUser.CurrentUserInfo.ID;
                    }
                    //string memberStr = Request["SMS.MemberID"];
                    if (!string.IsNullOrEmpty(memberStr))
                    {
                        var members = new List<Entity.MemberInfo>();
                        if (memberStr == "temp")
                        {
                            members = TempData["SelectedSMSMembers"] as List<Entity.MemberInfo>;
                        }
                        else
                        {
                            members = serviceMemberInfo.GetSelectedByIDs(memberStr);
                        }

                        if (members != null && members.Count > 0)
                        {

                            var telList = new List<string>();
                            telList.AddRange(members.Where(c => c.NoSMS && !string.IsNullOrEmpty(c.Tel)).Select(c => c.Tel).ToList());
                            smsObj.SMSTo = telList;
                            smsObj.Message = message.Remark;
                            tagSMS = smsObj.Send();
                            //tag = true;

                        }
                        var tagSave = false;
                        string actiontype = Request["actiontype"];
                        if (message.ID > 0 && actiontype != "goSend")
                        {
                            tagSave = serviceMessage.Update(message, members);
                        }
                        else
                        {
                            tagSave = serviceMessage.Add(message, members);
                        }

                        if (tagSave)
                        {
                            ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess + (!tagSMS ? ",短信发送失败:" 
                                                                                                            + smsObj.ErrorsMessage 
                                                                                                            + (smsObj.FailedTels != null && smsObj.FailedTels.Count>0?string.Join(",",smsObj.FailedTels):"") :
                                                                                                            string.Empty), navTabId, "", "closeCurrent");
                        }
                        else
                        {
                            ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
                        }
                    }
                    else
                    { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", ""); }
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }

        public ActionResult reEmail(int id = 0)
        {
            HanGu.Entity.Message message = new HanGu.Entity.Message();
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
                var vwmessage = serviceMessage.GetMsgByID(id);
                if (vwmessage != null)
                {
                    ViewData["membersID"] = string.Join(",", vwmessage.Select(c => c.MemberID).ToArray());
                    ViewData["membersName"] = string.Join(",", vwmessage.Select(c => c.RealName).ToArray());
                    ViewData["emails"] = string.Join(",", vwmessage.Select(c => c.Email).ToArray());
                }
                message.CreateTime = DateTime.Now;
                message.Creator = CurentUser.UserName;
            }

            ViewData["Attachments"] = serviceFileManage.GetByGuid(message.GUID);

            return View(message);
        }

        public ActionResult EmailMember(int id = 0)
        {
            HanGu.Entity.Message message = new HanGu.Entity.Message()
            {
                GUID = Helper.GetGuid,
                MemberID = 0,
                Type = 2,
                Title = string.Empty,
                Receiver = Request["emails"],
                CreateTime = DateTime.Now,
                Creator = CurentUser.UserName
            };
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
            }

            ViewData["Attachments"] = serviceFileManage.GetByGuid(message.GUID);
            if (Request["action"] == "rSend")
            {
                message.ID = 0;
            }
            ViewData["membersID"] = Request["membersID"];
            ViewData["membersName"] = Request["membersName"];

            return View(message);
        }
        public ActionResult Email(int id = 0)
        {
            int memberid = 0;
            int.TryParse(Request["memberid"], out memberid);
            HanGu.Entity.Message message = new HanGu.Entity.Message()
            {
                GUID = Helper.GetGuid,
                MemberID = memberid,
                Type = 2,
                Title = string.Empty,
                Receiver = Request["reciever"],
                CreateTime = DateTime.Now,
                Creator = CurentUser.UserName
            };
            if (id > 0)
            {
                message = serviceMessage.GetByID(id);
            }
            else
            {
                message.Receiver = Request["reciever"];
            }
            ViewData["Attachments"] = serviceFileManage.GetByGuid(message.GUID);
            if (Request["actiontype"] == "goSend")
            {
                message.Receiver = string.Empty;
            }
            return View(message);
        }

        [HttpPost]
        [ValidateInput(false)]
        public string Email(FormCollection collection)
        {
            try
            {
                string memberStr = Request["MemberIDs"];
                if (string.IsNullOrEmpty(memberStr))
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.InvalidMembers, navTabId, "", "");
                }
                else
                {
                    bool tagMail = false;
                    HanGu.Entity.Message message = new HanGu.Entity.Message();
                    string receivers = Request["Email.Receiver"] ?? Request["Receiver"];
                    TryUpdateModel(message, collection);
                    //string memberStr = Request["Email.MemberID"];
                    //var members = Request["action"] == "m" ? serviceMemberInfo.GetSelectedByIDs(memberStr) : serviceMemberInfo.GetSelectedByGroup(memberStr);
                    var members = new List<Entity.MemberInfo>();
                    if (memberStr == "temp")
                    {
                        members = TempData["SelectedEmailsMembers"] as List<Entity.MemberInfo>;
                    }
                    else
                    {
                        members = serviceMemberInfo.GetSelectedByIDs(memberStr);
                    }
                    message.Receiver = receivers;
                    message.Creator = CurentUser.UserName;
                    message.CreateTime = DateTime.Now;
                    if (!message.CreatorID.HasValue || message.CreatorID == 0)
                    {
                        message.CreatorID = CurentUser.CurrentUserInfo.ID;
                    }
                    //移动文件
                    string newpath = string.Empty;
                    MoveToFile(message.GUID, "Email", out  newpath);
                    #region 发EMAIL
                    MailMessage mail = new MailMessage();
                    var mailList = new List<string>();
                    mailList.AddRange(members.Where(c => c.NoEmail && !string.IsNullOrEmpty(c.Email)).Select(c => c.Email).ToList());
                    mail.EmailTo = mailList;
                    mail.MailSubject = message.Title;
                    mail.MailBody = message.Remark;
                    //添加附件
                    var fileManage = serviceFileManage.GetByGuid(message.GUID);
                    List<Attachment> Attachments = new List<Attachment>();
                    foreach (var item in fileManage)
                    {
                        Attachments.Add(new Attachment(Server.MapPath(item.FilePath)));
                    }
                    mail.Attachments = Attachments;
                    tagMail = mail.SendMailSMTP();
                    #endregion
                    //tag = true;
                    var tabSave = false;

                    string actiontype = Request["actiontype"];
                    if (message.ID > 0 && actiontype != "goSend")
                    {
                        tabSave = serviceMessage.Update(message, members);
                    }
                    else
                    {
                        tabSave = serviceMessage.Add(message, members);
                    }

                    if (tabSave)
                    {
                        ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess + (!tagMail ? "," + mail.ErrorMsg : string.Empty), navTabId, "", "closeCurrent");
                    }
                    else
                    {
                        ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
                    }
                }

            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }


        //
        // GET: /Message/Delete/5
        [HttpPost]
        public string Delete(int id, string guid)
        {
            try
            {
                try
                {
                    FileManageController filemanage = new FileManageController();
                    filemanage.DeleteExecute(guid);
                }
                catch { }
                serviceMessage.Delete(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }
        [HttpPost]
        public string DeleteMessageItem(int id, int guid)
        {
            try
            {
                bool result = serviceMessage.DeleteMessageItem(id, guid);
                if (result)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
                }
                else
                { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", ""); }
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }



        public ViewResult Confirm()
        {
            return View();
        }

    }
}
